<?php
declare (strict_types=1);

namespace app\technician_api\controller;

use think\facade\Log;
use Throwable;
use ba\ClickCaptcha;
use think\facade\Config;
use think\facade\Validate;
use app\common\facade\Token;
use app\admin\model\AdminLog;
use app\common\controller\Technician;
use think\facade\Db;

class Index extends Technician
{
    protected array $noNeedLogin = [];
    protected array $noNeedPermission = ['*'];
    protected $model;

    public function initialize (): void
    {
        parent::initialize();
        $this->model = new \app\admin\model\Technician;
    }

    /***
     * 技师报警
     */
    public function alarm ()
    {
        $params = $this->request->param();
        $area = \local\Area::lnglat($params['lng'], $params['lat']);

        $technicianInfo = Db::name('technician')->where('technician_id', $this->auth->technician_id)->find();
        $arr = [
            'technician_id'   => $this->auth->technician_id,
            'technician_name' => $technicianInfo['technician_name'],
            'tel'             => $this->auth->tel,
            'address'         => $area['result']['formatted_address'],
            'lng'             => $params['lng'],
            'lat'             => $params['lat'],
            'is_read'         => 0,
            'create_time'     => date("Y-m-d H:i:s", time()),
            'area_id'         => $technicianInfo['area_id'],
        ];
        // 启动事务
        Db::startTrans();
        try {
            Db::table("ba_technician_resort")
                ->insert($arr);
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->error("报警失败");
        }
        $this->success("报警成功");
    }

    /**
     * 修改技师接单状态
     */
    public function updategoWork ()
    {
        $params = $this->request->param();
        // 修改接单状态
        $this->auth->getTechnician()->is_go_work = $params['is_go_work'];

        // 修改开始结束时间
        preg_match_all('/\d+/', $params['start_order_time'], $start_order_time);
        preg_match_all('/\d+/', $params['end_order_time'], $end_order_time);

        $start_order_time = implode('', $start_order_time[0]);
        $end_order_time = implode('', $end_order_time[0]);
        if ((int)$start_order_time > (int)$end_order_time) {
            $this->error("接单开始时间不能大于结束时间");
        }
        $this->auth->getTechnician()->start_order_time = $params['start_order_time'];
        $this->auth->getTechnician()->end_order_time = $params['end_order_time'];


        $this->auth->getTechnician()->save();
        $this->success("修改成功");
    }

    /**
     * 首页信息
     * 头像 手机号 名称 在线状态
     * 总收益  总销量 总评分
     * 待服务订单数  进行中订单数 已完成订单数
     * 订单收入 订单总数 取消订单数
     */
    public function homeInfo ()
    {
        $params = $this->request->param();

        $lng = $params['lng'] ?? 0;
        $lat = $params['lat'] ?? 0;
        if ($lng != 0 && $lat != 0) {
            // 设置技师的经纬度
            $this->auth->getTechnician()->lng = $lng;
            $this->auth->getTechnician()->lat = $lat;
            $this->auth->getTechnician()->save();
        }


        $orderModel = new \app\admin\model\Order;

        // 技师总收益
//        $all_price = Db::name('giveaway_log')->where(
//            ['type' => 3, 'login_id' => $this->auth->technician_id]
//        )->sum('money');

        // 技师总收益
        $all_price = Db::table("ba_technician_money_log")
            ->where([
                'technician_id' => $this->auth->technician_id,
            ])->whereIn('type', [1, 2, 4, 6])->sum("money");

        $fare_price = Db::name('fare_order')->where('technician_id', $this->auth->technician_id)->where('fare_state', 'Paid')->sum('fare_pay_price');
        // 技师总销量
        $all_count = $orderModel->where([
            'technician_id' => $this->auth->technician_id,
            'order_state'   => 'Completed'
        ])->count();
        // 技师评分的均值
        $scoreNumber = Db::table("ba_order_evaluate")->where(['technician_id' => $this->auth->technician_id])->sum("score");
        $count = Db::table("ba_order_evaluate")->where(['technician_id' => $this->auth->technician_id])->count();
        $pingfen = 5;
        if ($scoreNumber != 0) {
            $pingfen = (int)$scoreNumber / $count;
        }

        // 订单管理 待服务
        $dfw = $orderModel->where([
            'technician_id' => $this->auth->technician_id,
            'order_state'   => 'Received'
        ])->count();
        // 进行中
        $jxz = $orderModel->where([
            'technician_id' => $this->auth->technician_id,
            'order_state'   => 'Paid'
        ])->count();
        // 已完成
        $ywc = $orderModel->where([
            'technician_id' => $this->auth->technician_id,
            'order_state'   => 'Completed'
        ])->count();

        //订单总数
        $dzs = $orderModel->where([
            'technician_id' => $this->auth->technician_id,
            'order_state'   => ['neq', 'ToBePaid']
        ])
            // ->where("order_state",'neq','ToBePaid')
            ->count();
        //已取消
        $yqx = $orderModel->where([
            'technician_id' => $this->auth->technician_id,
            'order_state'   => 'Canceled'
        ])->count();

        $open_id = '';
        if (!empty($this->auth->bind_user_id)) {
            $open_id = Db::name('user')->where('id', $this->auth->bind_user_id)->value('open_id');
        }

        $this->success("查询成功", [
            'userinfo'    => [
                'avatar'     => $this->auth->avatar,
                'tel'        => $this->auth->tel,
                'username'   => $this->auth->username,
                'is_go_work' => $this->auth->is_go_work,
                'open_id'    => $open_id
            ],
            'diamond'     => [
                'all_price' => bcadd((string)$all_price, (string)$fare_price, 2),
                'all_count' => $all_count,
                'pingfen'   => sprintf("%.1f", $pingfen),
            ],
            'order_left'  => [
                'dfw' => $dfw,
                'jxz' => $jxz,
                'ywc' => $ywc,
            ],
            'order_right' => [
                'ddsr' => $all_price,
                'ddzs' => $dzs,
                'qxdd' => $yqx,
            ]

        ]);
    }


    /**
     * 是否阅读过协议
     * @return void
     */
    public function isReadAgreement (): void
    {
        $ret = \app\admin\model\Technician::where('technician_id', $this->auth->technician_id)->value('is_read_agreement');
        $this->success("查询成功", ['is_read' => (bool)$ret]);
    }


    /**
     * 设置协议已读
     * @return void
     */
    public function setReadAgreementStatus (): void
    {
        $ret = \app\admin\model\Technician::where('technician_id', $this->auth->technician_id)->update(['is_read_agreement' => 1]);
        if (!$ret) {
            $this->error("设置失败");
        }
        $this->success("设置成功");
    }

    /**
     * 获取服务协议
     * @return void
     */
    public function getServiceSignAgreement (): void
    {
        $this->success("", [
            'title'   => "服务协议",
            'content' => get_sys_config('ServiceSignAgreement')
        ]);
    }
}